package com.film.util;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

public abstract class DBTemplate {

    private JDBCUtils jdbcUtils = JDBCUtils.getInstance();

    protected abstract Object processResultSet(ResultSet rs) throws SQLException;

    protected abstract PreparedStatement createPreparedStatement(Connection conn, String sql, List<Object> params) throws SQLException;
    public Object executeQuery(String sql, List<Object> params) {
        Connection conn = jdbcUtils.getConnection();
        PreparedStatement sta = null;
        ResultSet res = null;
        Object result = null;
        try {
            sta = createPreparedStatement(conn, sql, params);
            res = sta.executeQuery();
            result = processResultSet(res);
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            jdbcUtils.release(conn, sta, res);
        }
        return result;
    }

    public int executeUpdate(String sql, List<Object> params) {
        Connection conn = jdbcUtils.getConnection();
        PreparedStatement sta = null;
        int rows = 0;
        try {
        	sta = createPreparedStatement(conn, sql, params);
            rows = sta.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            jdbcUtils.release(conn, sta, null);
        }
        return rows;
    }
}

